import { EditOutlined, SearchOutlined, SyncOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import '../index.css'
import {Button, Form, Input, Table, Card, message, Tag, Popconfirm, Drawer, Select} from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import React, { useState, useEffect } from 'react'
import TableToolbar from '../../../../components/TableSetting/TableToolbar'
import { fetchRequest } from '../../../../utils/Request'
import { url } from '../../../../utils/url'
import { useDispatch, useSelector } from 'react-redux'
import actionType from './addressActionType'
import { useRequest } from '@umijs/hooks'
import AddAddress from "./AddAddress";
import {string} from "prop-types";



export default function AddressManageTable() {

    interface requestParams {
        index: number,
        num: number,
        collegeAreaId:string,
        building: string,
        unit: string
    }

    const addressInfo = useSelector((state: any) => {
        return state.addressManage;
    })

    const columns = [{
        title: '学校',
        dataIndex: 'collegeName',
        key: 'collegeName'
    },{
        title: '校区',
        dataIndex: 'collegeAreaName',
        key: 'collegeAreaName'
    }, {
        title: '栋',
        dataIndex: 'building',
        key: 'building'
    }, {
        title: "单元",
        dataIndex: "unit",
        key: "unit"
    },
    {
        title: "层",
        dataIndex: "floor",
        key: "floor"
    },{
        title: "房号",
        dataIndex: "room",
        key: "room"
    },{
            title: "地址",
            dataIndex: "addressName",
            key: "addressName"
    },{
        title: "操作", render: (record: any) => {
            return <small onClick={e => e.stopPropagation()}>
                <Popconfirm title="确定要删除？" onConfirm={e => {
                    deleteAddress.run({addressId: record.addressId.toString()})
                    //TODO 后需要进行删除操作
                }}>
                    <Tag className="tags-hover delete" color="#f50" icon={<DeleteOutlined/>}>删除</Tag>
                </Popconfirm>
            </small>
        }
    }
    ]


    const [form] = Form.useForm();
    const {Option} = Select;

    const [collegeAreaList,setCollegeAreaList] = useState<any[]>([]);
    const collegeAreaOption = collegeAreaList.map((d:any,index:number) => <Option value={d.collegeAreaId} key={index}>{d.collegeAndArea}</Option>);

    useEffect(() => {
        getCampusRequest()
    }, []);

    //点击搜索按钮
    function handleFinish(values: Store) {
        dispatch({
            type: actionType.SET_ADDRESS_PARAMS,
            payload: {
                collegeAreaId: typeof values.campus === "undefined" ? "" : values.campus,
                building: typeof values.ridgepole === "undefined" ? "" : values.ridgepole,
                unit: typeof values.unit === "undefined" ? "" : values.unit,
                index: 1,
                num: 10,
            }
        })
    }

    //点击重置按钮
    function handleReset() {
        form.resetFields();
        dispatch({ type: actionType.SET_ADDRESS_PARAMS,
            payload: { index: 1, num: 10, unit: "", building: "", collegeAreaId: "" } })
        //TODO 后续请求数据
    }

    //获取校区
    async function getCampusRequest()
    {
        try {
            const json = await fetchRequest(url.GET_CAMPUS, {collegeAndAreName: ''});
            console.log(json)
            if (json.success) {
                message.destroy();
                setCollegeAreaList(json.data);
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
        }
    }

    function handleCampusChange(){

    }

    //查询框
    const searchForm = (
        <Card className="search-form"> <Form form={form} layout="inline" initialValues={{ deptState: "1" }}
                                             onFinish={handleFinish} onReset={handleReset}>

            {/*<Form.Item className="form-control-item" name="deptId" label="校区" rules={[{ required: true, message: '必须要选择组织机构' }]}>*/}
            {/*    <TreeSelect className="search-form-item"*/}
            {/*                treeData={myData.campusData}*/}
            {/*        //         treeData={treeData}*/}
            {/*                treeDefaultExpandAll />*/}
            {/*</Form.Item>*/}
            <Form.Item className="form-control-item" name="campus" label="校区">
                {/*<Input className="search-form-item" />*/}
                <Select style={{ width: 300 }} onChange={handleCampusChange}>
                    {collegeAreaOption}
                </Select>
            </Form.Item>
            <Form.Item className="form-control-item" name="ridgepole" label="栋">
                <Input className="search-form-item" />
            </Form.Item>

            <Form.Item className="form-control-item" name="unit" label="单元">
                <Input className="search-form-item" />
            </Form.Item>

            <Form.Item className="form-control-item">
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit"
                        style={{ marginRight: '8px' }}>搜索</Button>
                <Button icon={<SyncOutlined />} htmlType="reset">重置</Button>

            </Form.Item>

        </Form></Card>)

    const [columnsKey, setcolumnsKey] = useState<any[]>([])
    const [realColumns, setrealColumns] = useState<any[]>([])
    const [addVisible, setaddVisible] = useState<boolean>(false)


// const addressdata=[{AddressId:"1",campus:"清水河校区",ridgepole:"1",unit:"1",room:"301"}]
    //点击刷新按钮
    function onRefresh() {
        // getDept.run()
        getAddress.run(addressInfo.requestAddressParams)
    }

    //点击新增按钮
    function onAdd() {
        getCampus.run();
        setaddVisible(true)
    }

    function onColumnsChange(checkedList: any[]) {
        setcolumnsKey(checkedList)
    }


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])

    //监听变化
    useEffect(() => {

    })

    const dispatch = useDispatch()

    //得到校区下拉菜单
    async function getCampusSelect() {
        try {
            const json = await fetchRequest(url.GET_CAMPUS,{collegeAndAreName: ''});
            console.log("校区数据")
            console.log(json.data)
            if (json.success) {
                dispatch({ type: actionType.GET_CAMPUS,
                    payload: json.data  })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getCampus = useRequest(getCampusSelect, {
        manual: true,
        loadingDelay: 200
    })

    //得到地址
    async function getAddressTable(params: requestParams) {
        console.log(params)
        try {
            const json = await fetchRequest(url.GET_ADDRESS_DETAIL, params);
            if (json.success) {
                dispatch({ type: actionType.GET_ADDRESS,
                    payload: { data: json.data, count: json.count ,
                    total:json.total} })
            }else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getAddress = useRequest(getAddressTable, {
        manual: true,
        loadingDelay: 200
    })


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])


    //监听变化
    useEffect(() => {
        getAddress.run(addressInfo.requestAddressParams)
    }, [addressInfo.requestAddressParams])



    //删除地址的接口
    async function deleteAddressRequest(params: { addressId: any }) {
        console.log(params)
        try {
            const json = await fetchRequest(url.DELETE_ADDRESS, params);
            if (json.success) {
                message.destroy();
                message.success("删除成功！");
                getAddress.run(addressInfo.requestAddressParams)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    const deleteAddress = useRequest(deleteAddressRequest, {
        manual: true,
        loadingDelay: 200
    })

    //点击分页的时候
    function handlePageChange(page: number) {
        dispatch({ type: actionType.SET_ADDRESS_PARAMS, payload: { index: page  } })
    }

    //新增成功
    function addSuccess() {
        message.destroy();
        message.success("新增成功!");
        setaddVisible(false);
        getAddress.run(addressInfo.requestAddressParams)
    }



    return (
        <div>
            {searchForm}
            <Card className="search-form-table">
                <TableToolbar tableName="地址清单" columns={columns}
                              onColumnsChange={onColumnsChange} onRefresh={onRefresh} onAdd={onAdd} />
                <Table
                    loading={getAddress.loading}
                    pagination={{ total: addressInfo.tableData.total, hideOnSinglePage: true, simple: true, onChange: handlePageChange,
                        current: addressInfo.requestAddressParams.index , showSizeChanger: false }}
               rowKey={(record: any) => record.addressId} columns={realColumns}
                    // dataSource={addressdata}
                    dataSource={addressInfo.tableData.data}
                />
            </Card>

            <Drawer width="60%" destroyOnClose visible={addVisible} title="新增地址信息" onClose={() => setaddVisible(false)}>
                <AddAddress  addSuccess={addSuccess}/>
            </Drawer>

        </div>
    )

}
